<?php
defined('IN_TS') or die('Access Denied.');

//全局通用定义
include_once '../public/php/defines.php';

//程序主体
switch($ts){
	case "": {
		if(intval($TS_USER['user']['userid']) > 0) {
			$arr = array(
				FLAG_RET => NO_ERR,
				FLAG_ERR_CODE => ERR_ALREADY_LOGIN
			);
		}
		
		break;
	}
	
	//执行登录
	case "do": {
	
		if($TS_USER['user'] != '') {
			$arr = array(
				FLAG_RET => NO_ERR,
				FLAG_ERR_CODE => ERR_ALREADY_LOGIN
			);
			break;
		}
		
		$email = trim($_POST['email']);
		
		$pwd = trim($_POST['pwd']);
		
		$cktime = $_POST['cktime'];
		
		if($email=='' || $pwd=='') {
			$arr = array(
				FLAG_RET => ERROR,
				FLAG_ERR_CODE => ERR_VAL
			);
			break;
		}
		
		$isEmail = $new['user']->findCount('user',array(
			'email'=>$email,
		));
		
		$strUser = $new['user']->find('user',array(
			'email'=>$email,
		));

		//此处预留其他登录接口
		
		if($isEmail == 0) {
			$arr = array(
				FLAG_RET => ERROR,
				FLAG_ERR_CODE => ERR_USER_NOT_FOUND
			);
			break;
		}
		
			
		if(md5($strUser['salt'].$pwd)!==$strUser['pwd']) {
			$arr = array(
				FLAG_RET => ERROR,
				FLAG_ERR_CODE => ERR_PASSWD
			);
			break;
		}
		
		//更新登录时间，用作自动登录
		$new['user']->update('user_info',array(
			'email'=>$email,
		),array(
			'ip'=>getIp(),  //更新登录ip
			'uptime'=>time(),   //更新登录时间
		));
		
		//用户信息
		$userData = $new['user']->find('user_info',array(
			'email'=>$email,
		));
		
		 //记住登录Cookie，根据用户Email和最后登录时间
		 if($cktime != ''){   
			 setcookie("ts_email", $userData['email'], time()+$cktime,'/');   
			 setcookie("ts_uptime", $userData['uptime'], time()+$cktime,'/');
		 }
			
		//用户session信息
		$sessionData = array(
			'userid' => $userData['userid'],
			'username'	=> $userData['username'],
			'areaid'	=> $userData['areaid'],
			'path'	=> $userData['path'],
			'face'	=> $userData['face'],
			'count_score'	=> $userData['count_score'],
			'isadmin'	=> $userData['isadmin'],
			'uptime'	=> $userData['uptime'],
		);

		$_SESSION['tsuser']	= $sessionData;
		
		//用户userid
		$userid = $userData['userid'];
		$username = $userData['username'];
		//返回session id到客户端
        $sessionid = session_id();
		
		//一天之内登录只算一次积分
		if(isset($strDate['uptime']) && $strDate['uptime'] < strtotime(date('Y-m-d'))){
			aac('user')->addScore($userid,'登陆',1);
		}
		
		$arr = array(
			FLAG_RET => NO_ERR,
			FLAG_USERNAME => $username,
			FLAG_SESSION_ID => $sessionid
		);
		
		break;
	}
	
	//退出	
	case "out": {
		unset($_SESSION['tsuser']);
		session_destroy();
		setcookie("ts_email", '', time()+3600,'/');   
		setcookie("ts_uptime", '', time()+3600,'/');
		
		$arr = array(
			FLAG_RET => NO_ERR
		);
		
		break;
	}
	
	default: {
		$arr = array(
            FLAG_RET => ERROR,
            FLAG_ERR_CODE => ERR_VAL
        );
		break;
	}
}

echo json_encode($arr);
